<?php
/**
 * 请求日志中间件
 *
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class RequestLog
{


    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $uri = explode('?', $request->getRequestUri());
        $uri = rtrim($uri[0], '/');
        $method = $request->method();

//        if (config('app.env') != 'production') {

        $isChatNotify = Str::contains($uri, '/chat/notify');
        $isPayNotify = Str::contains($uri, '/middle-ground/payments/notify');

        if (!$isChatNotify && !$isPayNotify) {
            return $next($request);
        }

        $params = $request->all();

        $userId = Auth::guest() ? 0 : Auth::id();

        $requestLogBody = [
            'uri' => $uri,
            'method' => $method,
            'params' => is_string($params) ? $params : json_encode($params),
            'user_id' => $userId,
            'created_at' => Carbon::now()->toDateTimeString()
        ];

        (new \App\Models\RequestLog())->insertLog($requestLogBody);
//        }

        return $next($request);
    }
}
